
#include "net.h"

static int download_fw  = -1;
static char n_progress  = 0;
static CURL *curlhandle = NULL;


size_t net_wirtefunc(void *ptr, size_t size, size_t nmemb, void *stream)
{
	int f = *(int *)stream;

	log_i("size=%d\n",size*nmemb);
	
	//return write(f, ptr, size*nmemb);
	return size*nmemb;
}


int net_progress_func(void *progress_data,  
	double t, /* dltotal */  
	double d, /* dlnow */  
	double ultotal,  
	double ulnow)  
{  
	static char old_n_progress = 0;


	n_progress =(char)(d*100.0/t);	
	if(0<=n_progress&&n_progress <= 99 && old_n_progress != n_progress)
	{
		old_n_progress = n_progress;
	}

	return 0;  
}



int net_http_download(const char *ip_str,const char * localpath,long timeout )
{
	int f;
    curl_off_t local_file_len = -1 ;
	int use_resume = 0;

    CURLcode r = CURLE_GOT_NOTHING;

	curlhandle = curl_easy_init();

	//***********************************************************************************************

	log_i("ip_str:localpath = %s:%s\n",ip_str,localpath);
	
	//***********************************************************************************************
    //采用追加方式打开文件，便于实现文件断点续传工作
    
	download_fw = open(localpath, O_RDWR|O_CREAT);
    if(download_fw == 0) 
	{
		log_e("fw error %s\n",localpath);
		return 0;
    }
	//***********************************************************************************************



	//***********************************************************************************************

	curl_easy_setopt(curlhandle, CURLOPT_URL, ip_str);
    curl_easy_setopt(curlhandle, CURLOPT_CONNECTTIMEOUT, timeout);  
    
	//设置文件续传的位置给libcurl
	//curl_easy_setopt(curlhandle, CURLOPT_RESUME_FROM_LARGE, use_resume?local_file_len:0);

    curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, &download_fw);
    curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, net_wirtefunc);

    curl_easy_setopt(curlhandle, CURLOPT_NOPROGRESS, 0);
    curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1L);
	curl_easy_setopt(curlhandle, CURLOPT_PROGRESSFUNCTION, net_progress_func);
	curl_easy_setopt(curlhandle, CURLOPT_PROGRESSDATA, 0); 
	//***********************************************************************************************

    r = curl_easy_perform(curlhandle);	
    close(download_fw);
	download_fw = -1;

	curl_easy_cleanup(curlhandle);
	curlhandle = NULL;
	
    if(r == CURLE_OK)
	{
		return 1;
	}
    else
	{
		log_e("http download end:%d:%s\n",r, curl_easy_strerror(r));	
		return 0;
    }
}








